using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using Util.Setvices.Filter;
using YN.DB;
using YN.WebApi.ResultProcess;
using static YN.WebApi.ResultProcess.SystemTextJsonConvert;

namespace Util.Setvices
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("AllowedHosts", builder =>
                {
                    builder.WithOrigins(Configuration.GetValue<string>("AllowedHosts").Split(","))
                            .AllowAnyMethod()
                            .AllowAnyHeader();
                });
            });
            services.AddControllers(options =>
            {
                options.Filters.Add<ExceptionMiddleware>();
                options.Filters.Add<ExecuteMiddleware>();
            }).AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Converters.Add(new IntConverter());
                options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
                options.JsonSerializerOptions.Converters.Add(new BoolNullConverter());
                options.JsonSerializerOptions.Converters.Add(new TimeSpanJsonConvert());
            });

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title = "工具类API",
                    Version = "v1",
                    Description = "工具类api接口 v1",
                    Contact = new OpenApiContact { Name = "wsl", Email = "" },
                });
                options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey
                });
                options.OperationFilter<SwaggerOperationFilter>();

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                options.IncludeXmlComments(xmlPath);
            });
            //达梦数据库配置
            //var dmconnect = Configuration["CONNECTIONSTRINGS_DM"];
            //if(!string.IsNullOrWhiteSpace(dmconnect))
            //{
            //    YNDMHelp.connectstr = dmconnect;
            //    YNDMHelp.syncStructure = false;
            //}

            services.SetDefaultSql(Configuration);
            services.AddSingleton(YNSql.Instance().fsql);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            string vPath = Configuration["VIRTUAL_PATH"];


            if (!string.IsNullOrWhiteSpace(vPath))
            {
                Console.WriteLine("ASPNETCORE_APP_PATH:" + vPath);

                //1、配置请求基地址（解决 view 的路径生成错误）：
                //app.Use((context, next) =>
                //{
                //    context.Request.PathBase = vPath;
                //    return next();
                //});

                // 2、配置静态文件基地址（不配置的话，用上面生成的地址无法访问到静态文件）：
                app.UsePathBase(vPath);
            }

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors("AllowedHosts");
            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseSwagger().UseSwaggerUI(c =>
            {
                string swaggerJsonBasePath = string.IsNullOrWhiteSpace(c.RoutePrefix) ? "." : "..";
                c.SwaggerEndpoint($"/swagger/v1/swagger.json", "util.api");

                //css 
                //c.InjectStylesheet("/css/swaggerdoc.css");
                //c.InjectStylesheet("/css/app.min.css");
                ////js 
                //c.InjectJavascript("/js/jquery.js");
                //c.InjectJavascript("/js/swaggerdoc.js");
                //c.InjectJavascript("/js/app.min.js");
            });

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            app.UseStaticFiles();
        }
    }
}
